﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using Common;

namespace EshubaAnalyser
{
    public static class Analyser
    {
        public const string WebSite = "http://www.eshuba.com";

        private static StringBuilder DownloadPage(string url)
        {
            StringBuilder result = new StringBuilder();
            WebResponse response = HttpTool.GetResponse(url, null, HttpMethods.Get);
            var webStream = response.GetResponseStream();
            if (webStream == null) return null;
            byte[] buffer = new byte[1024 * 8];
            try
            {
                List<byte> bytesList = new List<byte>();
                int readSize = webStream.Read(buffer, 0, buffer.Length);
                while (readSize > 0)
                {
                    bytesList.AddRange(buffer.Take(readSize));
                    readSize = webStream.Read(buffer, 0, buffer.Length);
                }
                result.Append(Encoding.Default.GetString(bytesList.ToArray()));
                return result;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static void DoAnalyse()
        {
            SetTopMenu();
        }

        private static void SetTopMenu()
        {
            StringBuilder pageContent = DownloadPage(WebSite + "/sort/index.htm");
            Regex regex = new Regex(@"(?is)(<td width=""17%"".*?<a\s*href=""(?<URL>[^""]*)""[^>]*>(?<NAME>.*?)</a></td>)",
                          RegexOptions.IgnoreCase | RegexOptions.Multiline);
            MatchCollection matches = regex.Matches(pageContent.ToString());
            foreach (Match match in matches)
            {
                string url = WebSite + match.Groups["URL"].Value.Replace("..", string.Empty);
                lock (EshubaCache.Instance)
                {
                    if (EshubaCache.Instance.MenuCache.Values.Any(lk => lk.Url == url)) continue;
                    EshubaMenu eshubaMenu = new EshubaMenu
                                    {
                                        Guid = Guid.NewGuid(),
                                        Text = match.Groups["NAME"].Value,
                                        Url = url
                                    };
                    EshubaCache.Instance.MenuCache.TryAdd(eshubaMenu.Guid, eshubaMenu);
                }
            }
            EshubaCache.Save();
        }

        public static List<EshubaMenu> GetChildMenu(EshubaMenu parentEshubaMenu)
        {
            StringBuilder childPage = DownloadPage(parentEshubaMenu.Url);
            Regex regex = new Regex(@"(?is)(<td width=""120"".*?<a\s*href=""(?<URL>[^""]*)""[^>]*>(?<NAME>.*?)</a></td>)",
                          RegexOptions.IgnoreCase | RegexOptions.Multiline);
            MatchCollection matches = regex.Matches(childPage.ToString());
            foreach (Match match in matches)
            {
                string url = WebSite + match.Groups["URL"].Value.Replace("..", string.Empty);
                lock (EshubaCache.Instance)
                {
                    if (EshubaCache.Instance.MenuCache.Values.Any(lk => lk.Url == url)) continue;
                    EshubaMenu eshubaMenu = new EshubaMenu
                    {
                        Guid = Guid.NewGuid(),
                        Text = match.Groups["NAME"].Value,
                        Url = url,
                        ParentGuid = parentEshubaMenu.Guid
                    };
                    EshubaCache.Instance.MenuCache.TryAdd(eshubaMenu.Guid, eshubaMenu);
                }
            }
            EshubaCache.Save();
            return EshubaCache.Instance.MenuCache.Where(item => item.Value.ParentGuid == parentEshubaMenu.Guid).Select(item => item.Value).ToList();
        }

        public static List<EshubaBook> GetClassifyBookList(EshubaMenu parentEshubaMenu)
        {
            StringBuilder childPage = DownloadPage(parentEshubaMenu.Url);
            Regex regex_page = new Regex(@"(?is)(页次：<b>[\d]*</b>/<b>(?<PAGECOUNT>[\d]*)</b>)",
                                         RegexOptions.IgnoreCase | RegexOptions.Multiline);
            Match match = regex_page.Match(childPage.ToString());
            int count = 1;
            count = int.Parse(match.Groups["PAGECOUNT"].Value);
            for (int i = 1; i <= count; i++)
            {
                if (i == 1)
                {
                    SetPageBookList(childPage.ToString(), parentEshubaMenu);
                }
                else
                {
                    string[] split__ = parentEshubaMenu.Url.Split(new[] { '_' });
                    string[] split_dot = split__[1].Split(new[] { '.' });
                    string back = i + "." + split_dot[1];
                    string nextUrl = split__[0] + "_" + back;
                    SetPageBookList(DownloadPage(nextUrl).ToString(), parentEshubaMenu);
                }
            }
            return EshubaCache.Instance.BookCache.Values.Where(lk => lk.ParentGuid == parentEshubaMenu.Guid).ToList();
        }

        public static void SetPageBookList(string pageContent, EshubaMenu parentEshubaMenu)
        {
            Regex regex_book = new Regex(@"(?is)(<td width=""100%"".*?<a\s*href=""(?<URL>[^""]*)""[^>]*target=_blank[^>]*><b>(?<NAME>.*?)<b></a></td>)",
                RegexOptions.IgnoreCase | RegexOptions.Multiline);
            MatchCollection matches = regex_book.Matches(pageContent);
            foreach (Match match in matches)
            {
                string url = WebSite + match.Groups["URL"].Value.Replace("..", string.Empty);
                lock (EshubaCache.Instance)
                {
                    if (EshubaCache.Instance.BookCache.Values.Any(lk => lk.Url == url)) continue;

                    EshubaBook eshubaMenu = new EshubaBook
                    {
                        Guid = Guid.NewGuid(),
                        Text = match.Groups["NAME"].Value,
                        Url = url,
                        ParentGuid = parentEshubaMenu.Guid
                    };
                    EshubaCache.Instance.BookCache.TryAdd(eshubaMenu.Guid, eshubaMenu);
                }
            }
        }

        public static string GetDownloadUrl(EshubaBook book)
        {
            StringBuilder bookPage = DownloadPage(book.Url);
            Regex regexSummary =
                new Regex(
                    @"(?is)(<td width=""572"" bgcolor=""#FFFFFF"" height=""30"" valign=""top"">[^>]
                    *<table border=""0"" width=""100%"">[^>]*<tr>[^>]*<td width=""100%"">(?<Summary>[^<>)]*))",
                    RegexOptions.IgnoreCase | RegexOptions.Multiline);
            Match match = regexSummary.Match(bookPage.ToString());
            book.Summary = match.Groups["Summary"].Value;
            Regex regexUrl =
                new Regex(@"(?is)(<a\s*href=""\.\.(?<URL>[^""]*?)&flag=1""[^>]*onclick=""return\s*JyDownH[^<>]*?"">)",
                    RegexOptions.IgnoreCase | RegexOptions.Multiline);
            Match matchUrl = regexUrl.Match(bookPage.ToString());
            book.DownloadUrl = WebSite + matchUrl.Groups["URL"].Value;
            EshubaCache.Save();
            return book.DownloadUrl;
        }
    }
}